<template>
	<view class="category-form-container" :style="{height: `${windowHeight}px`}">
		<u--form labelPosition="left" :model="modelData" :rules="formRules" ref="formRef" labelWidth="90">
			<u-form-item label="门店" prop="storeName" @click="storeShow = true;" borderBottom>
				<u--input v-model="modelData.storeName" border="none"></u--input>
			</u-form-item>
			<u-form-item label="上级分类" prop="parentName" @click="parentPickerShow = true;" borderBottom>
				<u--input v-model="modelData.parentName" border="none"></u--input>
			</u-form-item>
			<u-form-item label="分类名称" prop="name" borderBottom>
				<u--input v-model="modelData.name" border="none"></u--input>
			</u-form-item>
			<u-form-item label="分类图" prop="picUrl" borderBottom>
				<u-upload :fileList="modelData.picUrl" name="1" @afterRead="afterRead" :maxCount='1'
					@delete="deletePic"></u-upload>
			</u-form-item>
			<u-form-item label="分类排序" prop="sort" borderBottom>
				<u--input v-model="modelData.sort" border="none" type="number"></u--input>
			</u-form-item>
			<u-form-item label="开启状态" prop="status" borderBottom>
				<u-radio-group v-model="modelData.status">
					<u-radio label="开启" :name="0" :customStyle="{marginRight: '8px'}"></u-radio>
					<u-radio label="关闭" :name="1"></u-radio>
				</u-radio-group>
			</u-form-item>
		</u--form>
		<u-gap height="60" bgColor="#fff"></u-gap>
		<view style="width: 70%; margin: 0 auto;">
			<u-button @click="submitForm" type="primary" text="提交"></u-button>
		</view>
		<u-picker :show="storeShow" :columns="storedColumns" @cancel="storeShow = false"
				@confirm="handleStoreConfirm" keyName="name"></u-picker>
		<u-picker :show="parentPickerShow" :columns="parentPickerColumns" @cancel="parentPickerShow = false"
			@confirm="handleParentConfirm" keyName="name"></u-picker>
	</view>
</template>

<script>
	import {
		updateCategory,
		getCategory,
		getCategoryList,
		createCategory
	} from '@/api/mall/category.js'
	import config from '@/config'
	import {
		updateFile
	} from '@/api/upload.js'
	import { mapGetters } from 'vuex'
	export default {
		name: 'categoryForm',
		data() {
			return {
				parentPickerShow: false,
				parentPickerColumns: [
					[{
						name: '顶级分类',
						id: 0,
					}]
				],
				storeShow: false,
				storedColumns: [],
				modelData: {
					parentId: 0,
					id: undefined,
					name: '',
					picUrl: [],
					status: 0,
					storeId: undefined,
					storeName: undefined,
				},
				formRules: {
					parentName: [{
						required: true,
						message: '请选择上级分类',
						trigger: ['blur']
					}],
					name: [{
						required: true,
						message: '分类名称不能为空',
						trigger: ['blur']
					}],
					picUrl: [{
						validator: (rule, value, callback) => {
							const isValid = value.length > 0 &&
								value[0].status === 'success' &&
								value[0].url
							isValid ? callback() : callback(new Error('分类图片不能为空'))
						},
					}],
					sort: {
						required: true,
						type: 'number',
						message: '分类排序不能为空',
						trigger: ['blur', 'change'],
					},
					status: [{
						type: 'number',
						message: '开启状态不能为空',
						trigger: ['change']
					}],
					storeName: {
						required: true,
						message: '请选择门店',
						trigger: ['change']
					}
				}
			}
		},
		computed: {
			...mapGetters(['selectedStore', 'pickUpStore']),
			windowHeight() {
				return uni.getSystemInfoSync().windowHeight;
			}
		},
		async onLoad(params) {
			await this.$nextTick();
			this.resetForm();
			this.storedColumns = [this.pickUpStore];
			this.modelData.storeId = this.selectedStore.id;
			this.modelData.storeName = this.selectedStore.name;
			//查询门店下分类
			await this.initStoreTypeList();
			//编辑回显
			if(params?.id) {
				let d = await getCategory(params.id);
				this.modelData.id = d.data.id;
				this.modelData.parentId = d.data.parentId;
				this.modelData.parentName = this.parentPickerColumns[0].find(item => item.id == d.data.parentId ).name;
				this.modelData.name = d.data.name;
				this.modelData.status = d.data.status;
				this.modelData.sort = d.data.sort;
				this.modelData.picUrl = [{
					url: d.data.picUrl,
					status: "success",
					message: "",
				}];
			}
		},
		methods: {
			resetForm() {
				this.modelData = {
					parentId: 0,
					id: undefined,
					name: '',
					picUrl: [],
					status: 0,
					storeId: undefined,
					storeName: undefined
				}
				this.$refs.formRef.resetFields()
			},
			handleParentConfirm(arr) {
				this.parentPickerShow = false;
				this.modelData.parentName = arr.value[0].name;
				this.modelData.parentId = arr.value[0].id;
				this.$refs.formRef.validateField('parentName')
			},
			// 删除图片
			deletePic(event) {
				this.modelData.picUrl.splice(event.index, 1);
			},
			// 新增图片
			afterRead(event) {
				// 获取上传的文件对象
				const file = event.file;
				// 更新状态为“上传中”
				this.modelData.picUrl = [{
					...file,
					status: "uploading",
					message: "上传中",
				}];
				updateFile({
					url: file.url
				}).then((result) => {
					// 上传成功后更新状态和 URL
					this.$set(this.modelData.picUrl, 0, {
						...file,
						status: "success",
						message: "",
						url: result.data // 确保最终URL存在
					})
					this.$refs.formRef.validateField('picUrl')
				}).catch((error) => {
					// 上传失败后更新状态和错误信息
					this.modelData.picUrl = [{
						...file,
						status: "failed",
						message: "上传失败",
					}];
				});
			},
			submitForm() {
				this.$refs.formRef.validate().then(async res => {
					let { id, name, status, parentId, sort, storeId, picUrl: [{ url: picUrl } = {}] = [] } = this.modelData;
					let data = { id, name, picUrl, status, parentId, sort, storeId };
					if(this.modelData.id) {
						await updateCategory(data);
						this.$modal.msgSuccess('修改成功');
						setTimeout(() => {
							this.$tab.navigateBack('/pages/mall/product/category/index')
						}, 1000)
					} else {
						await createCategory(data);
						this.$modal.msgSuccess('新增成功');
						setTimeout(() => {
							this.$tab.navigateBack('/pages/mall/product/category/index');
						}, 1000)
					}
				}).catch(errors => {
					console.log(errors);
				})
			},
			//查询门店下分类
			async initStoreTypeList() {
				let {
					data
				} = await getCategoryList({
					parentId: this.modelData.parentId,
					storeId: this.modelData.storeId
				});
				this.parentPickerColumns[0] = [{
					name: '顶级分类',
					id: 0,
				}];
				this.parentPickerColumns[0] = [...this.parentPickerColumns[0], ...data];
			},
			//选择门店
			async handleStoreConfirm(arr) {
				if(arr.value[0].id != this.modelData.parentId) {
					this.modelData.parentId = undefined;
				}
				this.modelData.storeId = arr.value[0].id;
				this.modelData.storeName = arr.value[0].name;
				this.storeShow = false;
				this.initStoreTypeList();
			},
		},
		onReady() {
			this.$refs.formRef.setRules(this.formRules)
		},
	}
</script>

<style scoped>
	.category-form-container {
		display: flex;
		flex-direction: column;
		background-color: #fff;
		width: 100%;
		padding: 12px;
		box-sizing: border-box;
	}
</style>